import config from '@/config/index';

// 基础请求
export function baseRequest(
  url,
  method='GET',
  data = {},
  base = config.requestUrl
) {
  let header = {
	// 'content-type': 'application/json'
	'Content-Type': 'application/x-www-form-urlencoded',
	'userToken':uni.getStorageSync('token'),
  }
  return uni.request({
    url: base + url,
    data: data,
    method: method,
    header: header
  }).then(re => {
    let msg = '请求失败'
    let code = re.statusCode
	if(re instanceof Array){
		re = re[1];
	}
	console.log(re);
	if(re.data.code!==200){
		msg = re.data.errorMessage;
		// 未登录
		if(re.data.code==320){
			// 
			uni.showToast({
			    title:'去登录',
				icon: 'none',
			    duration: 2000
			});
			setTimeout(function() {
				uni.navigateTo({
					url: `/pages/public/login`
				})
			}, 200);
			
			// uni.showModal({
			//     title: '提示',
			//     content: '是否去登录',
			//     success: function (res) {
			//         if (res.confirm) {
			//             uni.navigateTo({
			//             	url: `/pages/public/login`
			//             })
			//         }
			//     }
			// });
			return false;
		}
		uni.showToast({
		    title:msg,
			icon: 'none',
		    duration: 2000
		});
		function RequestError(message, code = '') {
		  this.name = 'RequestError'
		  this.message = message || '请求失败'
		  this.code = code
		}
		RequestError.prototype = Object.create(Error.prototype)
		RequestError.prototype.constructor = RequestError
		throw new RequestError(msg, code)  
	}
	return re.data.result
	
  })
}

// post
export function p(url, data = {},base) {
  return baseRequest(url, 'POST', data, base)
}

// get
export function g(url, data = {},base) {
  return baseRequest(url, 'GET', data, base)
}

// delete
export function d(url, data = {},base) {
  return baseRequest(url, 'DELETE', data, base)
}

//put
export function put(url, data = {},base) {
  return baseRequest(url, 'PUT', data, base)
}
